package com.lal.sdk.util;

import com.lal.sdk.model.LalResponse;
import org.json.JSONObject;

import java.io.*;
import java.net.*;

public class HttpUtils {
    public static LalResponse post(String url, JSONObject json) {
        try {
            HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Content-Type", "application/json");
            conn.setDoOutput(true);

            try (OutputStream os = conn.getOutputStream()) {
                os.write(json.toString().getBytes("UTF-8"));
            }

            return readResponse(conn);
        } catch (Exception e) {
            return new LalResponse(-1, e.getMessage(), null);
        }
    }

    public static LalResponse get(String url) {
        try {
            HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();
            conn.setRequestMethod("GET");
            return readResponse(conn);
        } catch (Exception e) {
            return new LalResponse(-1, e.getMessage(), null);
        }
    }

    private static LalResponse readResponse(HttpURLConnection conn) throws IOException {
        int code = conn.getResponseCode();
        InputStream is = code == 200 ? conn.getInputStream() : conn.getErrorStream();
        BufferedReader reader = new BufferedReader(new InputStreamReader(is));
        StringBuilder sb = new StringBuilder();
        String line;
        while ((line = reader.readLine()) != null) sb.append(line);
        reader.close();

        JSONObject obj = new JSONObject(sb.toString());
        return new LalResponse(obj.optInt("error_code", code), obj.optString("desp", ""), obj.optString("data", null));
    }
}